#ifdef __linux__

#include <string.h>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>

/**
 * 启动服务
 * @param svr {char*} 服务名
 * @retuan {void} 
 */
void SvcStart(char *svr)
{
	FILE* fp = NULL;
	char command[128] = { 0 };
	sprintf(command, "systemctl start %s", svr);
	if ((fp = popen(command, "r")) == NULL)
	{
		return;
	}
	char buf[512] = { 0 };
	if ((fgets(buf, 512, fp)) == NULL)

	{
		pclose(fp);
		return;
	}
	printf("ret:%s\n",buf);
	pclose(fp);
};

/**
 * 停止服务
 * @param svr {char*} 服务名
 * @retuan {void} 
 */
void SvcStop(char *svr)
{
	FILE* fp = NULL;
	char command[128] = { 0 };
	sprintf(command, "systemctl stop %s", svr);
	if ((fp = popen(command, "r")) == NULL)
	{
		return;
	}
	char buf[512] = { 0 };
	if ((fgets(buf, 512, fp)) == NULL)
	{
		pclose(fp);
		return;
	}
	printf("ret:%s\n",buf);
	pclose(fp);
};

/**
 * 查询服务
 * @param svr {char*} 服务名
 * @param svc_state {int&} 服务状态
 * @retuan {void} 
 */
void SvcQuery(char* svr, int &svc_state)
{
	svc_state = 0;
	FILE* fp = NULL;
	char command[128] = { 0 };
	sprintf(command, "systemctl status %s | grep Active", svr);
	if ((fp = popen(command, "r")) == NULL)
	{
		return;
	}
	char buf[512] = { 0 };
	if ((fgets(buf, 512, fp)) == NULL)
	{
		pclose(fp);
		return;
	}
	std::string comment = std::string(buf,strlen(buf));
	//std::string::size_type _pos = comment.find("running");
	//开机启动的状态,static不可被管理,disable未启动,enable启动
	//dead关闭,exited已读取完系统配置,闲置 waiting等待, running正在进行, mounted挂载, plugged加载插件, failed系统配置错误
	if(std::string::npos != comment.find("running"))
	{
		svc_state = 2;
	}else if(std::string::npos != comment.find("listening")){
		svc_state = 2;
	}else{
		svc_state = 1;
	}
	// printf("ret:%s,state:%d\n",buf,svc_state);
	pclose(fp);	
};

#endif

